<template>
  <!--人资平台 员工管理 -->
  <div class="app-container">
    <!-- 增加员工 修改员工-->
    <comDialog
      :dialogVisible="dialogVisible"
      :title="title"
      :width="width"
      v-on:EventClose="EventClose"
    >
      <!-- 用户手机查找，确认用户是否存在 -->
      <el-form
        v-show="isCheckPhone"
        :model="dialogFormCheckPhone"
        label-width="100px"
        :rules="dialogFormCheckPhoneRules"
        class="checkPhone"
        ref="dialogFormCheckPhoneRef"
        @submit.native.prevent
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户手机号" prop="checkPhone">
              <el-input
                v-model="dialogFormCheckPhone.checkPhone"
                placeholder="用户手机号查询"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-button
              type="primary"
              @click="
                checkPhoneFunc(
                  'dialogFormCheckPhoneRef',
                  dialogFormCheckPhone.checkPhone
                )
              "
              >搜索</el-button
            >
          </el-col>
        </el-row>
      </el-form>

      <el-form
        v-show="isComDialogForm"
        :model="comDialogForm"
        label-width="100px"
        :rules="comDialogFormRules"
        ref="comDialogFormRef"
      >
        <!-- 员工姓名 -->
        <el-row :gutter="20">
          <el-col :span="18">
            <el-form-item label="员工姓名" prop="name">
              <el-input
                v-model="comDialogForm.name"
                placeholder="请输入用户名"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 角色（职位） 昵称 -->

        <el-row>
          <el-col>
            <el-form-item label="员工角色" prop="positionIds">
              <el-select
                v-model="positionList"
                multiple
                style="margin-left: 20px"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in dialogFormAddUser"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickname">
              <el-input
                v-model="comDialogForm.nickname"
                :disabled="isDisabled"
                placeholder="请输入昵称"
              ></el-input>
            </el-form-item>
          </el-col>
          <!-- level -->
          <!-- <el-col :span="12">
            <el-form-item label="职等"
                          prop="level">
              <el-input v-model="comDialogForm.level"
                        placeholder="请输入职等"></el-input>
            </el-form-item>
          </el-col> -->
        </el-row>

        <!-- 电话 邮箱 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input
                v-model="comDialogForm.phone"
                :disabled="isDisabled"
                placeholder="请输入手机号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col v-show="isCheckPhone" :span="12">
            <el-form-item label="邮箱地址" prop="email">
              <el-input
                v-model="comDialogForm.email"
                :disabled="isDisabled"
                placeholder="请输入邮箱"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 性别 状态 -->
        <el-row :gutter="20">
          <el-col v-show="isCheckPhone" :span="8">
            <el-form-item label="性别" prop="sex">
              <el-select
                v-model="comDialogForm.sex"
                placeholder="性别选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in dialogFormSex"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio v-model="radioStatus" label="0">开启</el-radio>
              <el-radio v-model="radioStatus" label="1">关闭</el-radio>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="18">
            <el-form-item label="入职时间" prop="entryTime">
              <!-- <el-input v-model="comDialogForm.entryTime"
                    placeholder="请输入入职时间"></el-input> -->
              <el-date-picker
                v-model="comDialogForm.entryTime"
                type="date"
                placeholder="请输入入职时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button @click="clickDialogCancel()">取消</el-button>
          <el-button type="primary" @click="clickDialogSave('comDialogFormRef')"
            >保存</el-button
          >
        </el-form-item>
      </el-form>
    </comDialog>

    <!-- 表单 -->
    <comForm
      :config="comFormConfig"
      :list="comFormList"
      @EventOnsubmit="EventOnsubmit"
    ></comForm>
    <!-- 新增 修改 -->
    <comMb8Button :config="comMb8Button" @handle="handleClick"></comMb8Button>
    <!-- 表格 -->
    <comTable
      class="comTable"
      :config="comTableConfig"
      :list="comTableList"
      :modes="comTableMode"
      :pagination="pagination"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
      @handleStatusChange="handleStatusChange"
    >
      <el-table-column label="操作" width="340" #default="scope">
        <el-button
          type="warning"
          plain
          size="mini"
          @click="handleTableCurrentChange('personal', scope)"
          >个人主页</el-button
        >
        <el-button
          type="success"
          plain
          size="mini"
          @click="handleTableCurrentChange('joblog', scope)"
          >工作日志</el-button
        >
        <el-button
          type="primary"
          plain
          size="mini"
          @click="handleTableCurrentChange('edit', scope)"
          >修改</el-button
        >
        <el-button
          type="danger"
          plain
          size="mini"
          @click="handleTableCurrentChange('delete', scope)"
          >删除</el-button
        >
      </el-table-column>
    </comTable>
  </div>
</template>

<script>
import comTable from "@/wss/components/comTable.vue";
import comForm from "@/wss/components/comForm.vue";
import comMb8Button from "@/wss/components/comMb8Button.vue";
import comDialog from "@/wss/components/comDialog.vue";

import { formatDate } from "@/wss/utils/dateFilter.js";
// 员工
import {
  getAddEmployee,
  getEmployeeList,
  getEditEmployee,
  getEmployeeInfo,
  getDeleteEmployee,
  getPositionId,
} from "@/wss/api/employee";
// 用户
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  exportUser,
  resetUserPwd,
  changeUserStatus,
  importTemplate,
} from "@/api/system/user";

// 角色（职位）
import { getRoleList } from "@/wss/api/role";

export default {
  components: {
    comTable,
    comForm,
    comMb8Button,
    comDialog,
  },
  data() {
    return {
      type: "add",
      //  ---------- 对话框 ----------

      dialogVisible: false, //显示对话框
      isCheckPhone: false, //显示phone搜索
      isComDialogForm: false, //显示  对话框内容

      isDisabled: false, // 是否禁用输入框
      title: "新增员工",
      width: "50%",

      dialogFormCheckPhone: {
        checkPhone: undefined, //搜索用户的电话
        // checkPhone: 15888888888,  //搜索用户的电话
      },
      // 新增用户-查询角色（职位）列表
      dialogFormAddUser: [],
      positionList: [], // 角色（职位）
      radioStatus: "0", //单选按钮状态
      //新增用户  --  性别列表
      dialogFormSex: [
        {
          label: "男",
          value: "0",
        },
        {
          label: "女",
          value: "1",
        },
        {
          label: "未知",
          value: "2",
        },
      ],
      // 新增员工对话框
      comDialogForm: {
        userId: undefined,
        name: undefined, //名称
        positionIds: [], //角色id （职位）
        nickname: undefined, //昵称
        // level: undefined, //职业等级 （职等）
        phone: undefined, //电话
        email: undefined, // 邮箱
        sex: undefined, //性别
        status: undefined, // 状态
        entryTime: undefined, //入职时间

        // password: undefined, // 密码
        // remark: undefined, //备注
        // // userId: Number(), //用户id
        // noID: undefined,
        // userName: undefined, //登录名字（英文，拼音）
        // postIds: [],
        // roleIds: [],
      },

      dialogFormCheckPhoneRules: {
        checkPhone: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            min: 11,
            max: 11,
            message: "请输入11位的手机号码",
            trigger: "blur",
          },
        ],
      },
      // 对话框表单规则
      comDialogFormRules: {
        positionList: [
          { required: true, message: "请选择角色", trigger: "change" },
        ],
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        nickname: [{ required: true, message: "请输入昵称", trigger: "blur" }],
        phone: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            min: 11,
            max: 11,
            message: "请输入11位的手机号码",
            trigger: "blur",
          },
        ],
        entryTime: [
          {
            required: true,
            message: "请选择日期",
            trigger: "change",
          },
        ],
      },
      // ---------- 表格配置 ----------
      comTableList: [
        // name
        // userId
        // nickname
        // positionIds
        // entryTime
        // phone
      ],
      comTableMode: [
        // {
        //   label: 'ID',
        //   mode: 'id',
        //   width: '60',
        // },
        {
          label: "ID",
          type: "index",
        },
        {
          label: "员工姓名",
          mode: "name",
          width: "120",
          showOverflowTooltip: true,
        },
        {
          label: "昵称",
          mode: "nickname",
        },
        {
          label: "工号",
          mode: "no",
          width: "60",
        },
        {
          label: "电话号码",
          mode: "phone",
        },
        // {
        //   label: '角色',
        //   mode: 'namePosition',
        //   showOverflowTooltip: true,
        // },
        // {
        //   label: "职等",
        //   mode: 'level'
        // },
        {
          label: "角色/职等",
          mode: "contentList",
          width: "140",
          lists: {
            // type:'warning',
            key_0: "id",
            key_1: "name",
            key_2: "level",
          },
        },
        {
          label: "状态",
          mode: "status",
        },
        {
          label: "入职时间",
          mode: "entryTime",
          showOverflowTooltip: true,
        },
      ],
      // 表格的配置（不针对行）
      comTableConfig: {
        loading: false,
      },

      // ---------- 表单配置 ----------
      comFormList: {
        modes: [
          {
            placeholder: "请输入员工姓名",
            formType: "input",
            label: "员工姓名",
            mode: "name",
            value: "",
          },
          {
            placeholder: "请输入员工工号",
            formType: "input",
            label: "员工工号",
            mode: "no",

            value: "",
          },
          {
            placeholder: "请输入手机号",
            formType: "input",
            label: "手机号",
            mode: "phone",
            value: "",
          },
          {
            placeholder: "请输入昵称",
            formType: "input",
            label: "昵称",
            mode: "nickname",
            value: "",
          },
          {
            placeholder: "请选择角色",
            formType: "select",
            label: "角色",
            mode: "positionIds",
            value: "",
            select: [
              {
                label: "1",
                value: "123",
              },
              {
                label: "2标题",
                value: "1233",
              },
              {
                label: "3",
                value: "3",
              },
            ],
          },
        ],
      },
      comFormMode: [
        {
          label: "快速筛选",
          mode: "screening",
          placeholder: "请筛选",
          formType: "select",
          options: {
            value: "valueaa",
            label: "labelaa",
          },
        },
        {
          label: "筛选",
          mode: "screen",
          placeholder: "筛选条件",
          formType: "input",
        },
        {
          label: "法条",
          mode: "law",
          placeholder: "请输入法条",
        },
        {
          label: "分类",
          mode: "classify",
          placeholder: "全部分类",
          formType: "select",
          options: {
            value: "value",
            label: "label",
          },
        },
        // {
        //   label: '生效时间',
        //   formType: 'date',
        //   pickerType: 'date',
        //   rangeSeparator: '-',
        //   startPlaceholder: '开始日期1112',
        //   endPlaceholder: '结束日期',
        // },
        {
          label: "上架时间",
          formType: "datePicker",
          pickerType: "date",
          rangeSeparator: "-",
          startPlaceholder: "开始日期1112",
          endPlaceholder: "结束日期",
        },
      ],
      comFormConfig: {},

      // 增删改 按钮
      comMb8Button: [
        {
          label: "增加",
          type: "primary",
          icon: "el-icon-plus",
          vHasPermi: "system:role:add",
          btnId: "add",
        },
        // {
        //   label: '修改',
        //   type: 'success',
        //   icon: 'el-icon-edit',
        //   vHasPermi: 'system:role:edit',
        //   btnId: 'edit',
        // },
      ],

      // 角色列表
      roleList: [
        // id,
        // name
      ],

      // 查询参数--分页
      pagination: {
        pageNum: 1, //第几页
        total: 0, // 总数
        pageSize: 10, //每页显示数
      },
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
      },
    };
  },
  created() {
    // this.$route.meta.title = 'aaaa'
  },
  mounted() {
    this.getEmployeeListMet(this.pagination);

    this.getRoleListMet();
    setTimeout(() => {
      this.handleFormRole();
    }, 1000);
  },
  methods: {
    // 添加员工
    async getAddEmployeeMet(data) {
      let result = await getAddEmployee(data).then((res) => res);
      console.log("添加员工", result);
      this.getEmployeeListMet(this.pagination);
    },
    // 获取员工列表
    async getEmployeeListMet(pagination = null) {
      this.comTableConfig.loading = true;
      let result = await getEmployeeList(pagination);
      if (result.code == "200") {
        console.log("y员工列表：", result);
        this.comTableList = result.rows;
        this.pagination.total = result.total;
        this.comTableConfig.loading = false;
      } else {
        this.$message({
          message: result.msg,
          type: "error",
        });
      }
      this.comTableConfig.loading = false;
    },
    // 修改员工接口
    async getEditEmployeeMet(data) {
      let result = await getEditEmployee(data);
      if (result.code == 200) {
        this.getEmployeeListMet();
      }
    },

    async getDeleteEmployeeMet(id) {
      console.log(id);
      let result = await getDeleteEmployee(id).then((res) => res);
      console.log(result);
      this.getEmployeeListMet();
    },
    // 通过 员工id 查询 所有的角色信息
    async getPositionIdMet(id) {
      return await getPositionId(id);
    },

    // 角色 （职位）获取
    async getRoleListMet(pagination = null) {
      let result = await getRoleList(pagination).then((res) => res);
      console.log("rrrr", result);
      if (result.code == 200) {
        this.dialogFormAddUser = [];
        result.rows.forEach((item) => {
          // 新增用户-查询角色（职位）列表
          this.dialogFormAddUser.push({
            label: item.name,
            value: item.idStr,
          });
        });
        this.roleList = result.rows;
        this.comTableConfig.loading = false;
      }
    },

    /** ruoyi -- 查询用户列表 */
    async getList(data) {
      let result = await listUser(data);
      if (result.total == 0) {
        this.$message({
          message: "没有当前选项",
          type: "error",
        });
      } else {
        this.isComDialogForm = true;
        this.isDisabled = true;

        let list = result.rows[0];
        this.comDialogForm = {
          userId: list.userId,
          nickname: list.nickName,
          phone: list.phonenumber,
          sex: list.sex,
          email: list.email,
        };
      }
    },
    /** ruoyi -- 查询用户列表  End*/

    handleFormRole() {
      // form 表单 角色
      this.comFormList.modes.forEach((item) => {
        if (item.formType == "select") {
          for (let i in this.roleList) {
            item.select.push({
              label: this.roleList[i].name,
              value: this.roleList[i].idStr,
            });
          }
        }
      });
    },

    // 表单操作
    EventOnsubmit(data) {
      this.comTableConfig.loading = true;
      let dataObj = {};
      data.forEach((item) => {
        Object.keys(item).forEach((x) => {
          if (item[x] !== null && item[x] !== "") {
            dataObj[x] = item[x];
          }
        });
      });
      this.getEmployeeListMet(dataObj);
    },

    // 新增
    handleClick(type, btnId) {
      // 新增
      if (btnId == "add") {
        this.dialogVisible = true;
        this.isCheckPhone = true;
        this.getRoleListMet();
      }
    },
    // dialog 保存按钮
    clickDialogSave(formRef) {
      this.$refs[formRef].validate((valid) => {
        if (valid) {
          this.comDialogForm.positionIds = this.positionList;
          this.comDialogForm.status = this.radioStatus;
          // this.comDialogForm.entryTime.valueOf(n   ew Date(this.comDialogForm.entryTime))

          // let aa = formatDate(1514772732000, 'yyyy/MM/dd hh:mm:ss')
          // console.log(this.comDialogForm, aa)
          // 时间转成时间戳valueOf
          // let t = d.valueOf(d)

          // 判断是 新增 还是修改
          if (this.type == "add") {
            console.log(this.comDialogForm);
            // return
            this.getAddEmployeeMet(this.comDialogForm);
          } else if (this.type == "edit") {
            let forms = this.comDialogForm;
            let data = {
              id: forms.idStr,
              name: forms.name,
              userId: forms.userId,
              nickname: forms.nickname,
              positionIds: forms.positionIds,
              entryTime: forms.entryTime,
              status: forms.status,
              phone: forms.phone,
            };
            this.getEditEmployeeMet(data);
          }

          this.dialogVisible = false;
          this.isCheckPhone = false;
          this.isComDialogForm = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // dialog 取消按钮
    clickDialogCancel() {
      this.dialogVisible = false;
      this.isCheckPhone = false;
      this.isComDialogForm = false;

      this.dialogFormCheckPhone = {
        checkPhone: undefined,
      };
      this.positionList = [];
      this.comDialogForm = {
        userId: undefined,
        name: undefined, //名称
        positionIds: [], //角色id （职位）
        nickname: undefined, //昵称
        // level: undefined, //职等
        phone: undefined, //电话
        email: undefined, // 邮箱
        sex: undefined, //性别
        status: undefined, // 状态
        entryTime: undefined, //入职时间
      };
    },

    // ------------------------------------------------------
    // 分页操作 S
    // pageSize 改变时会触发	每页条数
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.getEmployeeListMet(this.pagination);
    },

    // currentPage 改变时会触发	当前页
    handleCurrentChange(val) {
      this.pagination.pageNum = val;
      this.getEmployeeListMet(this.pagination);
    },
    // 分页操作 END

    // Table操作方法
    async handleTableCurrentChange(type, data) {
      let rows = data.row;
      this.comDialogForm = rows;

      // 修改 当前行
      if (type == "edit") {
        this.type = type;
        // 通过 员工id 查询 所有的角色信息 接口
        let res = await this.getPositionIdMet(rows.idStr);

        if (res.code == 200) {
          console.log("res:", res);
          res.data.forEach((item) => {
            this.positionList.push(String(item.id));
          });
          console.log("tanlse", this.comDialogForm);

          this.title = "编辑员工";

          this.dialogVisible = true; //显示对话框
          this.isCheckPhone = false; //显示phone搜索
          this.isComDialogForm = true; //显示  对话框内容
          this.isDisabled = false;
        }
      } else if (type == "delete") {
        // 删除
        this.getDeleteEmployeeMet(rows.idStr);
      }
    },

    // 状态更改
    handleStatusChange(row) {
      let positionIDS = [];
      row.contentList.forEach((item) => {
        positionIDS.push(`${item.idStr}`);
      });

      let data = {
        id: row.idStr,
        name: row.name,
        userId: row.userId,
        nickname: row.nickname,
        positionIds: positionIDS,
        entryTime: row.entryTime,
        status: row.status,
        phone: row.phone,
      };

      this.getEditEmployeeMet(data);
    },
    // 关闭弹窗
    EventClose(boolean) {
      // this.dialogVisible = boolean
      this.clickDialogCancel();
    },

    /**
     * 用途：用户入职成为员工
     *
     * 搜索登录用户的手机-判断用户是否存在，
     *
     */
    checkPhoneFunc(formRef, phone) {
      this.$refs[formRef].validate((valid) => {
        if (valid) {
          // 判断 员工列表是否存在当前电话号
          let isPhone = this.comTableList.some((item) => {
            return phone == item.phone;
          });
          if (isPhone == true) {
            this.$message({
              message: "搜索员工已存在",
              type: "success",
            });
          } else {
            // ruoyi 用户接口  phonenumber key固定
            this.getList({ phonenumber: phone });
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.checkPhone {
  .el-row {
    border-bottom: 1px solid #ddd;
  }
}
</style>